package com.dynamic.mybatis.web.mvc;

import com.dynamic.mybatis.core.intercept.DynamicMappedStatementHandler;
import com.dynamic.mybatis.core.metadata.DynamicMappedStatement;
import com.dynamic.mybatis.core.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;

@Component
public class MappedStatementRequestMappingRegister implements DynamicMappedStatementHandler {
    @Autowired
    private RequestMappingHandlerMapping requestMappingHandlerMapping;
    @Autowired
    private MappedStatementRequestExecuteHandler mappedStatementRequestExecuteHandler;

    Method executePostMethod;
    Method executeGetMethod;
    Method executeMethod;

    public MappedStatementRequestMappingRegister() {
        for (Method method : MappedStatementRequestExecuteHandler.class.getMethods()) {
            String methodName = method.getName();
            if ("executePost".equals(methodName)) {
                executePostMethod = method;
            } else if ("executeGet".equals(methodName)) {
                executeGetMethod = method;
            } else if ("execute".equals(methodName)) {
                executeMethod = method;
            }
        }
    }


    public void registerMapping(OPERATE operate, DynamicMappedStatement dms) {
        if (StringUtils.isBlank(dms)) {
            return;
        }
        String path = dms.getId().replaceAll("\\.", "/");
        // String path = prefix+"/{mappedStatementId}";

        RequestMappingInfo.Builder requestBuilder = RequestMappingInfo.paths(path);
        if (StringUtils.isNotBlank(dms.getMethod())) {
            requestBuilder.methods(RequestMethod.valueOf(dms.getMethod().method()));
        }
        RequestMappingInfo requestMappingInfo = requestBuilder.build();
        requestMappingHandlerMapping.unregisterMapping(requestMappingInfo);
        if (operate != OPERATE.DELETE && dms.isRest() && dms.isEnable()) {
            requestMappingHandlerMapping.registerMapping(requestMappingInfo, mappedStatementRequestExecuteHandler, executeMethod);
        }
    }

    @Override
    public void before(OPERATE operate, DynamicMappedStatement dms) {

    }

    @Override
    public void after(OPERATE operate, DynamicMappedStatement dms) {
        registerMapping(operate, dms);
    }
}
